package renguanyu.app.tools.controller;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.MapListHandler;

import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.fxml.FXML;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import renguanyu.app.tools.model.anjuke.CommunityUtil;
import renguanyu.app.tools.util.DbUtil;

public class AnjukeDataAnalyzeLineChartController {

	@FXML
	ComboBox<String> community;
	@FXML
	TableView<Map<String, Object>> dataTable;
	@FXML
	TableColumn<Map<String, Object>, String> createDate;
	@FXML
	TableColumn<Map<String, Object>, String> cnt;
	@FXML
	LineChart<String, Number> lineChart;
	@FXML
	Button queryDataBtn;
	@FXML
	CategoryAxis xAxis;
	@FXML
	NumberAxis yAxis;

	@FXML
	public void initialize() throws SQLException {
		community.getItems().addAll(CommunityUtil.data);
		community.setValue(community.getItems().get(0));

		createDate.setCellValueFactory(param -> new ReadOnlyObjectWrapper(param.getValue().get("created_at")));
		cnt.setCellValueFactory(param -> new ReadOnlyObjectWrapper(param.getValue().get("cnt")));

		XYChart.Series<String, Number> series = new XYChart.Series<>();
		series.setName(community.getSelectionModel().getSelectedItem());
	}

	@FXML
	public void queryData() throws SQLException {
		
		StringBuilder sql = new StringBuilder();
		sql.append("select  ");
		sql.append("created_at ");
		sql.append(",count(*) as cnt  ");
		sql.append("from anjuke_second_house  ");
		sql.append("where anxuan = 'Y' ");
		sql.append("and community_name = '" + community.getSelectionModel().getSelectedItem() + "' ");
		sql.append("group by created_at  ");
		sql.append("order by created_at desc  ");
		List<Map<String, Object>> listMap = DbUtil.getQueryRunner().query(sql.toString(), new MapListHandler());
		dataTable.getItems().setAll(listMap);

		sql = new StringBuilder();
		sql.append("select  ");
		sql.append("created_at ");
		sql.append(",count(*) as cnt  ");
		sql.append("from anjuke_second_house  ");
		sql.append("where anxuan = 'Y' ");
		sql.append("and community_name = '" + community.getSelectionModel().getSelectedItem() + "' ");
		sql.append("group by created_at  ");
		sql.append("order by created_at asc  ");
		listMap = DbUtil.getQueryRunner().query(sql.toString(), new MapListHandler());
		XYChart.Series<String, Number> series = new XYChart.Series<>();
		series.setName(community.getSelectionModel().getSelectedItem());
		listMap.forEach(e -> {
			series.getData().add(new XYChart.Data<String, Number>(e.get("created_at").toString(),
					Double.valueOf(e.get("cnt").toString())));
		});
		lineChart.getData().addAll(series);
	}

}
